package fun.qu_an.minecraft.mini_games_helper.client.mixin;

import com.llamalad7.mixinextras.lib.apache.commons.tuple.Pair;
import com.mojang.serialization.Codec;
import fun.qu_an.minecraft.mini_games_helper.client.handle.ForceOptionHelperVanilla;
import fun.qu_an.minecraft.mini_games_helper.client.hook.SimpleOptionsHook;
import fun.qu_an.minecraft.mini_games_helper.client.util.GameOptionsHelper;
import net.minecraft.client.option.SimpleOption;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;

import java.util.function.Consumer;

@Mixin(SimpleOption.class)
public class SimpleOptionMixin<T> implements SimpleOptionsHook<T> {
	@Unique
	private SimpleOption.ValueTextGetter<T> mgh$valueTextGetter;

	@Inject(method = "getValue",
		at = @At(value = "HEAD"), cancellable = true)
	private void forceOption(CallbackInfoReturnable<T> cir) {
		@SuppressWarnings("unchecked")
		SimpleOption<T> option = ForceOptionHelperVanilla.getForced((SimpleOption<T>) (Object) this);
		if (option != null) {
			cir.setReturnValue(option.getValue());
		}
	}

	@Inject(method = "<init>(Ljava/lang/String;Lnet/minecraft/client/option/SimpleOption$TooltipFactory;Lnet/minecraft/client/option/SimpleOption$ValueTextGetter;Lnet/minecraft/client/option/SimpleOption$Callbacks;Lcom/mojang/serialization/Codec;Ljava/lang/Object;Ljava/util/function/Consumer;)V",
		at = @At("RETURN"))
	private void keepSomeValue(String key, SimpleOption.TooltipFactory<T> tooltipFactory, SimpleOption.ValueTextGetter<T> valueTextGetter, SimpleOption.Callbacks<T> callbacks, Codec<T> codec, T defaultValue, Consumer<T> changeCallback, CallbackInfo ci) {
		this.mgh$valueTextGetter = valueTextGetter;
		if (GameOptionsHelper.isLoaded()) {
			return;
		}
		System.out.println(key);
		Pair<SimpleOption<?>, Class<?>> pair = Pair.of((SimpleOption<?>) (Object) this, defaultValue.getClass());
		// shit key...
		ForceOptionHelperVanilla.putVanilla(key.replace('_', '.'), pair);
		ForceOptionHelperVanilla.putVanilla(key.replace('.', '_'), pair);
		String key1 = key.substring(key.indexOf(".") + 1);
		if (key1.equals(key)) {
			return;
		}
		ForceOptionHelperVanilla.putVanilla(key1, pair);
	}

	@Override
	public SimpleOption.ValueTextGetter<T> mgh$getValueTextGetter() {
		return mgh$valueTextGetter;
	}
}
